<script setup>
import {onUnmounted, ref, shallowRef} from "vue";

// const themeComponents=[NormalPage,Demo1Page]
const files = require.context('@/views/pushPages/', true, /\.vue$/)
const themeComponents=[]
const names = []
// 组件导入
files.keys().forEach((key) => {
  /**
   *
   * 获取vue文件名
   * 法一：用正则表达式匹配
   * key.replace(/^\.\/(.*)\.\w+$/, '$1')
   * 法一：path.basename获取vue文件名
   * import path from 'path'
   * path.basename(path[, ext])
   * path.basename() 方法会返回 path 的最后一部分。 尾部的目录分隔符会被忽略。
   **/
      // 获取文件名 法一
  var name = key
          .split('/')
          .pop()
          .replace(/\.\w+$/, '');
  names.push(name)
  themeComponents[name] = files(key).default || files(key)
})
// const pageComponents = shallowReactive(themeComponents);


const props = defineProps(['taskId','uid'])

// const sseSource = new EventSource("/api/sse/1");
const sseSource = new EventSource('/api/task/conn/'+props.taskId+'?uid='+props.uid)

// 连接打开
sseSource.onopen = function () {
  console.log("连接打开");
}

// 连接错误
sseSource.onerror = function (err) {
  console.log("连接错误:", err);
}

// 接收到数据
sseSource.onmessage = function (event) {
  console.log("接收到数据:", event.data);
  handleReceiveData(event.data)
}
function closeTest(){
  sseSource.close()
}

onUnmounted(()=>{
  console.log("组件卸载")
  sseSource.close()
})
let pageComp=shallowRef(themeComponents['NormalPage'])

let dataMessage=ref('')

function handleReceiveData(data) {
  let dataJson={}
  try{
    dataJson=JSON.parse(data)
  }catch (e){
    console.error('数据解析异常:',data)
  }
  if(dataJson.tag){
    console.log(themeComponents[dataJson.tag])
    pageComp.value=undefined == themeComponents[dataJson.tag]?themeComponents['NormalPage']:themeComponents[dataJson.tag]
  }
  dataMessage.value=dataJson.info
}
</script>

<template>
  <el-button @click="closeTest">测试</el-button>
  <component :is="pageComp" :data-message="dataMessage" />
</template>

<style scoped>

</style>
